//
//  ApplePurchasePlugin.swift
//  Runner
//
//  Created by apple on 2020/7/21.
//

import UIKit
import StoreKit

// 内购插件
class ApplePurchasePlugin:  NSObject, FlutterPlugin {
    
    //主要用来回调 flutter 方法
    var channel: FlutterMethodChannel
    
    init(channel: FlutterMethodChannel) {
        self.channel = channel
        super.init()
    }
   
    //注册插件
    static func register(with registrar: FlutterPluginRegistrar) {
       let channel = FlutterMethodChannel(name: "bl_apple_purchase", binaryMessenger: registrar.messenger())
       let instance = ApplePurchasePlugin(channel: channel)
       registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        
        let productId: String? = call.arguments as? String
        if productId == nil || productId!.isEmpty {
            result(FlutterMethodNotImplemented)
            return
        }
        
        switch call.method {
        case "startPurchase":
            startPurchase(productId: productId!)
            break
        default:
            result(FlutterMethodNotImplemented)
            break
        }
    }
    
    //开始内购流程
    func startPurchase(productId: String) {
        addPayObserver()
        starBuyToAppStore(productId: productId)
    }
    
    // 开始购买
    func starBuyToAppStore(productId: String){    //需要传入商品id
     print("call starBuyToAppStore")
       
     if SKPaymentQueue.canMakePayments() {
         self.getProductInfo(productId: productId) //充值金额
     }else{
         onPayError(errMsg: "您的手机没有打开程序内付费购买功能")
     }
    }
        
    // 下面的ProductId应该是事先在itunesConnect中添加好的，已存在的付费项目。否则查询会失败。
    func getProductInfo(productId:String){
        print("call getProductInfo: \(productId)")
        let productIdentifiers = Set<String>([productId])
        let productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
        productsRequest.delegate = self
        productsRequest.start()
    }
    
    func addPayObserver() {
        SKPaymentQueue.default().add(self)
    }
    
    deinit {
        SKPaymentQueue.default().remove(self)
    }
    
    //支付失败
    func onPayError(errMsg: String) {
        channel.invokeMethod("onPayError", arguments: errMsg)
    }
    
    //完成上次购买
    func onFinishLastTransaction() {
        channel.invokeMethod("onFinishLastTransaction", arguments: nil)
    }
    
    //完成支付 二次验证
    func onCompleteTransaction(params: Dictionary<String, Any>) {
        channel.invokeMethod("onCompleteTransaction", arguments: params)
    }
    
}

extension ApplePurchasePlugin: SKProductsRequestDelegate,SKPaymentTransactionObserver{
   
    ///查询的回调函数
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        print("productsRequest \(response.products)")
        let myProduct = response.products
        if myProduct.count == 0 {
            onPayError(errMsg: "获取商品信息失败")
            return
        }
        ///调起支付框
        let payment = SKMutablePayment(product: myProduct[0])
        SKPaymentQueue.default().add(payment)
    }
    
    
    ///用户购买的操作结果
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        
        print("paymentQueue")
        
        for transaction in transactions {
            print("商品 id: \(transaction.payment.productIdentifier)")
            switch transaction.transactionState {
            case .purchased: ///交易完成
                print("paymentQueue purchased")
                completeTransaction(transaction: transaction)
                break
            case .failed: ///交易失败
                print("paymentQueue failed")
                failedTransaction(transaction: transaction)
                break
            case .restored: ///已购买
                print("paymentQueue restored")
                restoreTransaction(transaction: transaction)
                break
            case .purchasing: ///商品添加进列表
                print("paymentQueue purchasing")
                break
            default:
                print("paymentQueue default")
                break
            }
        }
    }
    
    /**
    * 交易完成  后台二次验证充值
    */
    func completeTransaction( transaction:SKPaymentTransaction){
        
        print("completeTransaction \(transaction)")
        
        let productIdentifier = transaction.payment.productIdentifier
    
        do {
            
            ///验证字符串
            let receipt = try Data(contentsOf: Bundle.main.appStoreReceiptURL!).base64EncodedString(options: .lineLength64Characters)
            
            var param = [:] as [String : Any]
            //param["userId"] = USERINFO.userId()  //用户主键
            param["appleReceipt"] = receipt      //验证字符串
            param["tradeId"] =  productIdentifier          //商品id
            param["transactionId"] = transaction.transactionIdentifier     //苹果订单号
            //二次验证回调
            onCompleteTransaction(params: param)
            //移除transaction购买操作
            SKPaymentQueue.default().finishTransaction(transaction)

        } catch {
            print("异常: \(error)")
        }
    }
    
    
    /**
    * 交易失败
    */
    
    func request(_ request: SKRequest, didFailWithError error: Error) {
        print(error)
        onPayError(errMsg: "交易失败")
        print("didFailWithError")
    }
    
    func failedTransaction( transaction:SKPaymentTransaction){
        if transaction.error != nil {
//            BLTool.showMsg(Text: "用户取消购买")
            onPayError(errMsg: "取消购买")
        } else {
//            BLTool.showMsg(Text: "购买失败")
            onPayError(errMsg: "购买失败")
        }

        SKPaymentQueue.default().finishTransaction(transaction)
        print("failedTransaction")

    }
    
    /**
    * 对于已购商品，处理恢复购买的逻辑
    */
    func restoreTransaction( transaction:SKPaymentTransaction){
        print("restoreTransaction")
        SKPaymentQueue.default().finishTransaction(transaction)
       onFinishLastTransaction()
    }
    
    
}

